#include "networkserver.h"

NetworkServer::NetworkServer(QObject *parent) : QTcpServer(parent) {
  anyClientConnected = false;
}

void NetworkServer::startServer() {
  server = new QTcpServer(this);

  connect(server, SIGNAL(newConnection()), this, SLOT(newConnection()));

  bool state = false;
  if (clientIP == "any")
    state = server->listen(QHostAddress::Any, tcpPort);
  else
    state = server->listen(QHostAddress(clientIP), tcpPort);

  if (!state) {
    qDebug() << "Server: Could not start";
  }
  else {
    qDebug() << "Server: Started, listening on port" << tcpPort;
  }
}

void NetworkServer::newConnection() {
  socket = server->nextPendingConnection();

  qDebug() << "Server: Client connected from" << socket->peerAddress().toString();

  connect(socket, SIGNAL(readyRead()), this, SLOT(dataReceived()));
  connect(socket,SIGNAL(disconnected()), this, SLOT(disconnected()));
  connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(networkError(QAbstractSocket::SocketError)));

  socket->setSocketOption(QAbstractSocket::LowDelayOption,"1");
  socket->setSocketOption(QAbstractSocket::KeepAliveOption,"1");

  anyClientConnected = true;

  emit clientConnected();
}

void NetworkServer::dataReceived() {
  //Get the data from the network socket
  QByteArray data = socket->readAll();

  emit dataReady(data);
}

void NetworkServer::disconnected() {
  qDebug() << "Server: Client disconnected";
  anyClientConnected = false;

  emit clientDisconnected();
}

void NetworkServer::sendData(QByteArray data) {
  if (socket->isOpen()) {
    socket->write(data);
  }
}

void NetworkServer::setClientIP(QString ip) {
  clientIP = ip;
}

void NetworkServer::setHostIP(QString hostIP) {
  serverIP = hostIP;
}

void NetworkServer::setTcpPort(quint16 port) {
  tcpPort = port;
}

QString NetworkServer::getClientIP() {
  return(clientIP);
}

QString NetworkServer::getHostIP() {
  return(serverIP);
}

quint16 NetworkServer::getTcpPort() {
  return(tcpPort);
}

bool NetworkServer::isClientConnected() {
  return(anyClientConnected);
}

void NetworkServer::networkError(QAbstractSocket::SocketError error) {
  emit socketError(error,socket->errorString());
}
